package com.swq.java.code.chapter13.code34;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Machine implements Runnable {
    private final Lock machineLock = new ReentrantLock();  //创建外部锁
    int data = 100;  //共享数据

    public void run() {
        machineLock.lock();  //用外部锁来同步
        try {  //try代码块中的语句为原子操作
            data++;
            Thread.currentThread().sleep(1000);
            data--;
            System.out.println(Thread.currentThread().getName() + ": data=" + data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            machineLock.unlock();  //在finally代码块中释放锁
        }
    }

    public static void main(String args[]) throws Exception {
        Machine machine = new Machine();
        for (int i = 0; i < 10; i++) {  //创建10个线程，都执行同一个Machine对象的run()方法
            Thread thread = new Thread(machine);
            thread.start();
        }
    }
}